﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace HostingRedisServer
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            var logger = host.Services.GetRequiredService<ILogger<Program>>();
            var redisServer = host.Services.GetRequiredService<IRedisServer>();
            AppDomain.CurrentDomain.ProcessExit += async (sender, e) =>
            {
                await StopRedisAndExit(redisServer, logger);
            };
            try
            {
                host.Run();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                await StopRedisAndExit(redisServer, logger);
            }
            Thread.Sleep(Timeout.Infinite);
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .AddEnvironmentVariables()
    .AddCommandLine(args)
    .Build();

            var builder = Host.CreateDefaultBuilder(args);
            builder.ConfigureServices((hostContext, services) =>
            {
                //var configuration = hostContext.Configuration;

                services.AddSingleton<IConfiguration>(configuration);// 注册配置
                services.Configure<RedisOption>(configuration.GetSection(RedisOption.Name));
                services.AddSingleton<IRedisServer, RedisServer>();
                services.AddHostedService<RedisHostedService>();
            });
            return builder;
        }

        static async Task StopRedisAndExit(IRedisServer redisServer, ILogger logger)
        {
            try
            {
                logger.LogInformation("正在停止 Redis 服务器...");
                await redisServer.StopAsync();
                logger.LogInformation("Redis 服务器已停止");

                RedisProcessKiller.KillAllRedisProcessesByName();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "停止 Redis 时发生错误");
            }
        }
    }
}
